from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.core.cache import caches,cache
import csv
import time
from fundinfo.fundmodel import *
from analysis.basic_data import *
from analysis.price_analysis import *
import numpy as np

def getRateYear(code):
    path = settings.ANALYSIS_DIR + "/year_rate.csv"
    csvReader = None
    try:
        csvReader = csv.reader(open(path, encoding='utf-8'))
    except:
        return None
    for item in csvReader:
        if item[0] == code:
            return float(item[1]), float(item[2]), float(item[3])

def getMonthStr(day):
    tmp = day.split("-")
    return tmp[0] + tmp[1]

def getMonthIncome(transData):
    lastMonth = ""
    income = 0.0
    incomeMonth = []
    startAdd = False
    for item in transData:
        day = item.date
        month = getMonthStr(day)

        if startAdd == False and item.income.incomeDay != 0.0:
            startAdd = True

        if lastMonth != month:
            if lastMonth != "" and startAdd:
                incomeMonth.append([lastMonth, round(income, 2)])
            income = item.income.incomeDay
            lastMonth = month
        else:
            income = income + item.income.incomeDay
    incomeMonth.append([lastMonth, round(income, 2)])
    return incomeMonth

def readFundBasicInfo():
    path = settings.ANALYSIS_DIR + "/index_info.csv"
    csvReader = None
    try:
        csvReader = csv.reader(open(path, encoding='utf-8'))
    except:
        return None

    fundlist = []

    count = 0
    for item in csvReader:
        if count == 0:
            count = count + 1
            continue
        fundlist.append(item)
    return fundlist

def getFundBasicInfo(code):
    info = readFundBasicInfo()
    for item in info:
        if item[0] == code:
            return item
    return None

# Create your views here.
def getFundInfo(request, code):
    info = {}
    info['code'] = code

    price = PriceAnalysis(code)
    price.readPriceData()

    fundInfo = FundInfoBriefData()
    fundInfo = fundInfo.getExsitRecord(code)
    if fundInfo == None:
        return render(request,"fundinfo.html", info)

    monitorMaxRate, monitorMaxDay, monitorMinRate, monitorMinDay, monitorResult = price.rateMonitor(fundInfo.maxDrawDown1Y)

    info['info'] = fundInfo
    info['incomeTotal'] = fundInfo.totalIncome
    info['income'] = fundInfo.curIncome
    info['incomePercent'] = fundInfo.curIncomeRate
    info['units'] = fundInfo.curUnits
    info['incomeLstData'] = BasicData.getFundIncomeInfo(code)

    array = []
    count = 0
    for fund in reversed(info['incomeLstData']):
        count = count + 1
        if count > 22:
            break
        array.append(fund.jjjz)

    a = np.array(array)
    info['avg'] = round(np.mean(a), 2)

    lastIncome = None
    if len(info['incomeLstData']) != 0:
        lastIncome = info['incomeLstData'][-1]
        info['lastDayIncome'] = info['incomeLstData'][-1]
        info['price'] = lastIncome.jjjz
        info['totalCost'] = lastIncome.totalCost
        info['cost'] = lastIncome.cost
        info['totalPrice'] = fundInfo.curValue

    info['incomeMonth'] = BasicData.getFundMonthIncome(code)

    info['maxDrawDown'] = BasicData.getMaxDrawDownYear(code)
    info['yearRate'] = BasicData.getYearIncomeRate(code)
    info['civilYearRate'] = BasicData.getCivilYearRate(code)[0:5]

    # monitorMaxRate, monitorMaxDays, monitorMinRate, monitorMinDays, monitorResult
    info['monitorMaxRate'] = monitorMaxRate
    info['monitorMaxDay'] = monitorMaxDay
    info['monitorMinRate'] = monitorMinRate
    info['monitorMinDay'] = monitorMinDay
    info['monitorResult'] = monitorResult

    return render(request,"fundinfo.html", info)

class FastIncome:
    name = ""
    code = ""
    date = ""
    cost = 0.0
    units = 0.0
    income = 0.0
    incomeRate = 0.0

def fastIncome(request):
    obj = Trading.objects.filter(units__gt=0,cost__gt=0).order_by("-id")[:50]
    if obj == None:
        return

    fundList = {}
    incomeLst = []
    
    for trading in obj:
        code = trading.code

        fund = None
        if code in fundList:
            fund = fundList[code]
        else:
            price = PriceAnalysis(code)
            price.readPriceData()
            fund = price
            fundList[code] = fund

        jjjz = fund.price[-1].jjjz
        value = jjjz * trading.units
        income = value - trading.cost
        incomeRate = income / trading.cost
        a = FastIncome()
        a.code = code
        a.income = round(income, 2)
        a.incomeRate = round(incomeRate * 100, 2)
        a.date = trading.date
        a.cost = round(trading.cost, 2)
        a.units = round(trading.units, 2)

        fundName = FundName.objects.filter(code=code)
        if fundName != None:
            a.name = fundName[0].name

        incomeLst.append(a)
        print(code, a.cost, trading.date, incomeRate, income)
    info = {}
    info["funds"] = incomeLst
    return render(request,"fastincome.html", info)



